package com.ruoyi.oss.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.ffmpeg.FFmpegProcessor;
import com.ruoyi.oss.entity.Chunk;
import com.ruoyi.oss.entity.UploadRes;
import com.ruoyi.oss.service.IOssService;
import com.ruoyi.oss.template.OssTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/oss")
public class OssTestController {

    /**
     * 目录路径,这个路径需要包含test.info文件，test.key文件和test.mp4文件
     */
    private static final String PATH = "D:\\aaa\\";

    @Autowired
    private OssTemplate ossTemplate ;

    @Autowired
    private IOssService iossService ;

    /**
     * 处理文件上传GET请求
     * 验证上传的文件块，是否允许浏览器再次发送POST请求（携带二进制文件的请求流，FormData）
     *
     * @param chunk 文件MD5值
     * @return 文件块
     */
    @GetMapping("/file/upload")
    public AjaxResult uploadGet(@ModelAttribute Chunk chunk, HttpServletResponse response) {
        //boolean flag = fileService.fileUploadGet(chunk);
        /*Integer code = 200;
        if (!flag) {
            code = 304;
        }
        response.setStatus(code);
        return ResultUtils.result(code, chunk);*/
        return AjaxResult.success() ;
    }

    /**
     * 处理文件上传POST请求
     * 将上传的文件存放到服务器内
     *
     * @param chunk    文件块
     * @param response 响应
     * @return 上传响应状态
     */
    @PostMapping("/file/upload")
    public AjaxResult uploadPost(@ModelAttribute Chunk chunk, HttpServletResponse response) {
        UploadRes upload = iossService.upload(chunk);
        return AjaxResult.success(upload);
    }

    @PostMapping("/file/merge")
    public AjaxResult merge(Chunk chunk) {
        UploadRes upload = iossService.merge(chunk);
        return AjaxResult.success(upload);
    }




















    @RequestMapping("/uploadData")
    public AjaxResult uploadData(String filename, MultipartFile file) {
        Date now = DateUtils.getNowDate();
        String year = DateUtils.parseDateToStr("yyyy", now);
        String month = DateUtils.parseDateToStr("MM", now);
        String day = DateUtils.parseDateToStr("dd", now);
        String object = year + "/" + month + "/" + day + "/" + UUID.fastUUID() ;
        ossTemplate.putFile("test", object +"/" + filename, file);
        return AjaxResult.success();
    }

    @GetMapping("/upload/chunk")
    public AjaxResult upload() {
        String url =  "" ;
        Date now = DateUtils.getNowDate();
        String year = DateUtils.parseDateToStr("Y", now);
        String month = DateUtils.parseDateToStr("Y", now);
        String day = DateUtils.parseDateToStr("Y", now);
        String object = year + "/" + month + "/" + day + "/" + UUID.fastUUID() + ".chunk " ;
        url = ossTemplate.generalUploadPath("test", object);
        return AjaxResult.success(url);
    }


    @GetMapping("/index")
    public String index() {
        String srcBucketName = "appdata" ;
        String fileName  = "/2021-11-25/ceb8f0f0-4267-46c9-8c5f-8be7be76ed61";
        String destFileName  = "/2021-11-30/ceb8f0f0-4267-46c9-8c5f-8be7be76ed61";

        String destBucketName = "test" ;
        ossTemplate.copyFile(srcBucketName, fileName, destBucketName);
        ossTemplate.copyFile(srcBucketName, fileName, destBucketName,destFileName);
        return "测试！！！";
    }




    @PostMapping("/uploadToM3u8")
    public void uploadToM3u8() throws Exception {
        InputStream inputStream = new BufferedInputStream(new FileInputStream(PATH + "[电影天堂www.dytt89.com]追虎擒龙-2021_HD国语中字.mp4"));
        String m3u8Url = "http://localhost:8080/oss/upload/test.m3u8";
        String infoUrl = "http://localhost:8080/oss/preview/test.info";
        FFmpegProcessor.convertMediaToM3u8ByHttp(inputStream, m3u8Url, infoUrl);
    }

    @PostMapping("/convertToMp4")
    public void convertToMp4() throws Exception {
        InputStream inputStream = new FileInputStream("F:\\迅雷下载\\阳光电影www.ygdy8.com.怒火·重案.2021.HD.1080P.国粤双语中字.mkv");
        String url = ossTemplate.getPlayPath("appdata", "/vod/Hard-Target-2.BD.720p.rmvb");
        FFmpegProcessor.convertVideoToMP4(new URL(url), "D:\\BaiduNetdiskDownload\\Hard-Target-2.BD.720p.mp4");
        //FFmpegProcessor.convertVideoToMP4(PATH + "nonghuozhongan.mkv");
    }


    @RequestMapping("/upload/{fileName}")
    public void upload(HttpServletRequest request, @PathVariable("fileName") String fileName) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        FileWriter writer = new FileWriter(PATH + fileName);
        writer.writeFromStream(inputStream);
        IoUtil.close(inputStream);
    }

    /**
     * 预览加密文件
     */
    @RequestMapping("preview/{fileName}")
    public void preview(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        FileReader fileReader = new FileReader(PATH + fileName);
        fileReader.writeToStream(response.getOutputStream());
    }

    /**
     * 下载加密文件
     */
    @GetMapping("download/{fileName}")
    public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        FileReader fileReader = new FileReader(PATH + fileName);
        fileReader.writeToStream(response.getOutputStream());
    }
}
